package com.wanggsx.library.util;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zkt on 2018-8-13.
 * Description:
 */

public class UtilsFragment {
    static Map<Integer, UtilsFragment> mapFragment = new HashMap<>();
    private Fragment preFragment;
    private int mContainerId;

    public static UtilsFragment getInstance(int containerId) {
        if (mapFragment.get(containerId)==null){
            UtilsFragment instance = new UtilsFragment();
            instance.mContainerId = containerId;
            mapFragment.put(containerId,instance);
        }
        return mapFragment.get(containerId);
    }

    public void setAddedFragentForInit(Fragment firstShowFragment){
        this.preFragment = firstShowFragment;
    }

    public void switchFragment(FragmentActivity activity, Fragment targetFragment) {
     /*   WeakReference<FragmentActivity> weakReference = new WeakReference<>(activity);
        FragmentActivity weakActivity = weakReference.get();*/
        if (targetFragment==preFragment){
            return;
        }
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            transaction.add(mContainerId, targetFragment, targetFragment.getClass().getName());
            if (preFragment != null) {
                transaction.hide(preFragment);
            }
        } else {
            transaction.show(targetFragment)
                    .hide(preFragment);
        }
        preFragment = targetFragment;

        transaction.commitAllowingStateLoss();
    }
}
